<template>
  <van-dialog class="van-dialog" v-model:show="showDialog" :show-confirm-button="false">
    <div class="popup-container">
      <van-image :src="posterUrl"></van-image>
      <van-icon class="close" name="close" size="40" color="#f3f3f3" @click="closeDialog" />
    </div>
  </van-dialog>
</template>

<script setup>
import { getLocalStorageWithExpiry, setLocalStorageWithExpiry } from '@/tool/index.js'
import { ref, onMounted, computed, watch } from 'vue'

import { fetchPopUpAd } from '@/api/index.js'

import { useStore } from '@/stores/index'
const store = useStore() //store 实例

// 添加标志位确保 弹窗广告  getPopUpAd() 只执行一次
let hasFetchedPopUpAd = false

//弹窗广告图
const props = defineProps({
  showPopUpAd: Boolean,
})

const emit = defineEmits(['toggle:dialog'])

//弹窗广告图
const posterUrl = ref('')
const showDialog = ref(false)

// 监听 props 变化同步内部状态
watch(
  () => props.showPopUpAd,
  (newVal) => {
    console.log('newVal', newVal)
    showDialog.value = newVal
  },
)

onMounted(() => {
  getPopUpAd()
})

//获取弹窗广告
const getPopUpAd = async () => {
  // 确保只执行一次
  if (hasFetchedPopUpAd) return
  hasFetchedPopUpAd = true
  // 确保 store 中有 siteOID 和 siteCityOID
  if (!store.locationCity.siteOID || !store.locationCity.siteCityOID) {
    console.warn('缺少必要的参数，无法获取弹窗广告')
    return
  }
  const {
    result: {
      dialogs,
      categorys: {
        rooms: [{ items }],
      },
    },
  } = await fetchPopUpAd(store.locationCity.siteOID, store.locationCity.siteCityOID)
  // 当前弹窗广告存在
  if (dialogs?.length > 0) {
    posterUrl.value = dialogs[0].posterUrl

    //判断是否已经弹窗过
    if (!getLocalStorageWithExpiry('open_screen_pop-up_ad')) {
      emit('toggle:dialog', true)
      setLocalStorageWithExpiry('open_screen_pop-up_ad', true, 1 * 24 * 60 * 60 * 1000) // 24小时
    }
  }

  if (items.length > 0) {
    // console.log('items', items)
    store.setCategoryIcons(items)
  }
}

//关闭弹窗广告
const closeDialog = () => {
  emit('toggle:dialog', false)
}
</script>

<style scoped lang="scss">
:deep(.van-popup.van-popup--center.van-dialog) {
  background: transparent !important;
}

.popup-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;

  .close {
    margin-top: 20px;
  }
}
</style>
